package com.tj.jinzao.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.business.session.emoji.EmoticonPickerView;
import com.netease.nim.uikit.business.session.emoji.IEmoticonSelectedListener;
import com.netease.nim.uikit.business.session.emoji.MoonUtil;
import com.tj.jinzao.R;
import com.tj.jinzao.base.BaseActivity;
import com.tj.jinzao.callback.IUploadView;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.model.Article;
import com.tj.jinzao.model.Target;
import com.tj.jinzao.presenter.PublicArticlePresenter;
import com.tj.jinzao.utils.ToastUtils;
import com.tj.jinzao.utils.Utils;
import com.tj.jinzao.widgets.PictureDialog;


import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.luck.picture.lib.config.PictureConfig.CHOOSE_REQUEST;

/**
 * 发布日记2
 * Created by wjy on 2019/1/12.
 */
public class PublicTopic2Activity extends BaseActivity<PublicArticlePresenter> implements IUploadView<String>, View.OnClickListener, IEmoticonSelectedListener, View.OnTouchListener {

    @BindView(R.id.ll_content_layout)
    LinearLayout mContentLayout;
    @BindView(R.id.iv_add_pic)
    ImageView mAddView;
    @BindView(R.id.emoticon_picker_view)
    EmoticonPickerView mPickerView;

    private String mTitle;
    private boolean mChooseVideo;
    private List<String> mImageList;
    private String mContent;
    private String mVideoPath;

    @Override
    protected PublicArticlePresenter createPresenter() {
        return new PublicArticlePresenter(this);
    }

    @Override
    public int getLayoutResource() {
        return R.layout.activity_public_topic_2;
    }

    @Override
    protected int getLeftButtonResId() {
        return R.mipmap.ic_back;
    }

    @Override
    protected CharSequence getRightButtonText() {
        return "下一步";
    }

    @Override
    protected void clickRightButton() {
        getContent();
        if (TextUtils.isEmpty(mContent)) {
            ToastUtils.showToast(this, "请输入内容");
            return;
        }
        Article article = new Article();
        article.setTitle(mTitle);
        article.setContent(mContent);
        article.setVideo(mChooseVideo);
        article.setVideoUrl(mVideoPath);
        if (mImageList != null && mImageList.size() > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            for (String path : mImageList) {
                if (stringBuilder.length() != 0) stringBuilder.append(",");
                stringBuilder.append(path);
            }
            article.setImgurls(stringBuilder.toString());
        }
        if(mImageList==null||mImageList.size()==0){
            ToastUtils.showToast(this,"请至少选择一张图片");
            return;
        }
        startActivity(new Intent(this, PublicTopic3Activity.class).putExtra("article", article));
        finish();
    }

    @Override
    protected void setupView() {
        mImageList = new ArrayList();
        mTitle = getIntent().getStringExtra("title");
        refresh();
    }

    private void refresh() {
        getContent();
        setContent();
    }

    @OnClick(R.id.iv_add_pic)
    void addPic() {
        PictureDialog dialog = new PictureDialog(this);
        if (mChooseVideo) dialog.setHideImage(true);
        else if (mImageList.size() > 0) dialog.setHideVideo(true);
        dialog.show();
    }

    @OnClick(R.id.iv_add_emo)
    void chooseEmo() {
        if (mPickerView.getVisibility() == View.VISIBLE) {
            mPickerView.setVisibility(View.GONE);
        } else {
            mPickerView.setVisibility(View.VISIBLE);
            Utils.hideSoftInput(this, getWindow().getDecorView());
            mPickerView.show(this);
        }
    }

    private void addImage(String path) {
        mImageList.add(path);
        if (mImageList.size() > 0 && mChooseVideo) mAddView.setVisibility(View.GONE);
        else if (mImageList.size() > 4) mAddView.setVisibility(View.GONE);
        getContent();
        mContent += Constant.ARTICLE_TAG;
        setContent();
    }

    private void getContent() {
        StringBuilder stringBuilder = new StringBuilder();
        int child_count = mContentLayout.getChildCount();
        for (int i = 0; i < child_count; i++) {
            View view = mContentLayout.getChildAt(i);
            if (view instanceof LinearLayout) {
                EditText editText = view.findViewById(R.id.et_content);
                stringBuilder.append(editText.getText().toString().trim());
            } else {
                stringBuilder.append(Constant.ARTICLE_TAG);
            }
        }
        mContent = stringBuilder.toString();
    }

    private void setContent() {
        mPresenter.setContentView(getLayoutInflater(), mContent, mImageList, mChooseVideo, mContentLayout, this);
        for (int i = 0; i < mContentLayout.getChildCount(); i++) {
            View view = mContentLayout.getChildAt(i);
            if (view instanceof LinearLayout) {
                EditText editText = view.findViewById(R.id.et_content);
                editText.setOnTouchListener(this);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 结果码不等于取消时候
        if (resultCode != Activity.RESULT_CANCELED) {
            switch (requestCode) {
                case CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    for (LocalMedia localMedia : selectList) {
                        mChooseVideo = localMedia.getPictureType().startsWith("video");
                        String path = localMedia.isCompressed() ? localMedia.getCompressPath() : localMedia.getPath();
                        if (mChooseVideo) {
                            mVideoPath = path;
                            Bitmap bitmap = Utils.getVideoThumb(path);
                            path = Constant.SD_TEMP_IMAGE + System.currentTimeMillis() + ".jpg";
                            Utils.saveBitmap(path, bitmap);
                        }
                        addImage(path);
                    }
                    break;
            }
        }
    }

    @Override
    public void onUploadSuccess(String path, String url) {

    }

    @Override
    public void onCaseSuccess(List<Target> list) {

    }

    @Override
    public void onCaseFailed(String msg) {

    }

    @Override
    public Activity getContext() {
        return this;
    }

    @Override
    public void onRequestSuccess(String s) {

    }

    @Override
    public void onRequestNoData(String message) {

    }

    @Override
    public void onRequestError(String error_message) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_delete:
                String path = (String) view.getTag(R.id.data);
                int index = mImageList.indexOf(path);
                mImageList.remove(path);
                int child_count = mContentLayout.getChildCount();
                int count = 0;
                for (int i = 0; i < child_count; i++) {
                    View view1 = mContentLayout.getChildAt(i);
                    if (view1 instanceof RelativeLayout) {
                        if (index == count) {
                            mContentLayout.removeView(view1);
                            break;
                        } else {
                            count++;
                        }
                    }
                }
                if (mImageList.size() == 0) {
                    mChooseVideo = false;
                    mAddView.setVisibility(View.VISIBLE);
                }
                refresh();
                break;
        }
    }

    @Override
    public void onEmojiSelected(String key) {
        for (int i = mContentLayout.getChildCount(); i > -1; i--) {
            View view = mContentLayout.getChildAt(i);
            if (view instanceof LinearLayout) {
                EditText editText = view.findViewById(R.id.et_content);
                String text = editText.getText().toString().trim() + key;
//                editText.append(key);
                MoonUtil.identifyFaceExpression(NimUIKit.getContext(), editText, text, ImageSpan.ALIGN_BOTTOM);
                editText.setSelection(text.length());
                break;
            }
        }
    }

    @Override
    public void onStickerSelected(String categoryName, String stickerName) {

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        mPickerView.setVisibility(View.GONE);
        return false;
    }
}
